var crypto = require('./crypto-js.js')
var base64 = require('./base64.js')

console.log(crypto, 'crypto')
// 'aes-128-cbc'

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId
  this.sessionKey = sessionKey
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // base64 decode
  var sessionKey = crypto.enc.Base64.parse(this.sessionKey);
  encryptedData = crypto.enc.Base64.parse(encryptedData);
  iv = crypto.enc.Base64.parse(iv);
	console.log( 'sessionKey', sessionKey );
	console.log( 'encryptedData', encryptedData );
	console.log( 'iv', iv );
  try {
    var decipher = crypto.AES.decrypt(encryptedData, sessionKey, { iv, mode: crypto.mode.CBC, padding: crypto.pad.Pkcs7 });
		console.log(decipher, 'decipher');
		let decryptedStr = decipher.toString(crypto.enc.Utf8);
		return decryptedStr.toString();
  } catch (err) {
    throw new Error('Illegal Buffer')
  }

  if (decoded.watermark.appid !== this.appId) {
    throw new Error('Illegal Buffer')
  }

  return decoded
}

module.exports = WXBizDataCrypt
